package com.sise.bl.service.impl;

import com.sise.bl.dao.CartDao;
import com.sise.bl.dao.ProductDao;
import com.sise.bl.dao.UserDao;
import com.sise.bl.entity.Cart;
import com.sise.bl.entity.Product;
import com.sise.bl.entity.User;
import com.sise.bl.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;

@Transactional
@Service(value = "cartService")
public class CartServiceImpl implements CartService {
    @Autowired
    @Qualifier(value = "cartDao")
    private CartDao cartDao;

    @Autowired
    @Qualifier(value = "userDao")
    private UserDao userDao;

    @Autowired
    @Qualifier("productDao")
    private ProductDao productDao;

    @Override
    public void createCart(Integer uid, String pid) {
        Cart cart = null;
        //1.我们需要判断是否已经存在了！
        List<Cart> carts = cartDao.hasCart(uid, Integer.valueOf(pid));
        //根据商品 id 查询商品
        Product product = productDao.selectProductByPid(Integer.valueOf(pid));
        if (carts.size() != 0) {
            cart = carts.get(0);
            //添加过购物车，修改即可
            cart.setCnum(cart.getCnum() + 1);
            BigDecimal cnumbig = new BigDecimal(cart.getCnum());
            BigDecimal count = product.getPprice().multiply(cnumbig);
            cart.setCcount(count);
            cartDao.updateCart(cart);
        } else {
            //不能存在，添加即可

            //根据用户 id 查询用户
            User user = userDao.selectUserById(uid);
            cart = new Cart();
            cart.setCnum(1);
            cart.setCcount(product.getPprice());
            cart.setProduct(product);
            cart.setUser(user);

            cartDao.insertCart(cart);
        }

    }

    @Override
    public List<Cart> findAll(Integer uid) {
        List<Cart> carts = cartDao.selectCartsByUid(uid);
        return carts;
    }

    @Override
    public void deleteCartByCid(String cid) {
        Cart cart = cartDao.selectCartsByCid(Integer.valueOf(cid));
        cartDao.deleteCart(cart);
    }

    @Override
    public void updateCartByCid(String cid, String price, String cnum) {
        BigDecimal cnumbig = new BigDecimal(cnum);
        BigDecimal pricebig = new BigDecimal(price);

        BigDecimal count = pricebig.multiply(cnumbig);

        Cart cart = cartDao.selectCartsByCid(Integer.valueOf(cid));
        cart.setCcount(count);
        cart.setCnum(Integer.parseInt(cnum));

        cartDao.updateCart(cart);
    }

    @Override
    public void clearCart(String uid) {
//        List<Cart> carts = cartDao.selectCartsByUid(Integer.valueOf(uid));
//        for (Cart cart : carts) {
//            cartDao.deleteCart(cart);
//        }
        cartDao.deleteCartByUid(uid);
    }
}
